<?php
namespace WDB\Analyzer;
use WDB,
    WDB\Exception;

/**
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 *
 */
class Table extends TableView
{
    /**@var string|NULL table name of the time dependency table or NULL if this table is not time dependent */
    protected $timeDependencyTable = NULL;

    /**@var bool true if this is a time dependency support table (do not display alone)*/
    protected $isTimeDependency = FALSE;

    public function __construct($tableName, $tableComment, WDB\Analyzer\iSchema $schema, WDB\SQLDriver\iSQLDriver $driver)
    {
        parent::__construct($tableName, $tableComment, $schema, $driver);
        foreach ($this->tableColumns->foreign as $name=>$key)
        {
            foreach ($key->columns as $column)
            {
                $this->columns[$column]->addForeignKey($name);
            }
        }
    }

    public function onSchemaConstructed()
    {
        parent::onSchemaConstructed();
        $this->initTimeDependencyTable();
    }

    protected function initTimeDependencyTable()
    {
        $tdDefault = $this->name.'~td';
        if (isset($this->annotations->timeDependency))
        {
            $this->timeDependencyTable = $this->annotations->last('timeDependency')->text;
        }
        elseif (in_array($tdDefault, array_keys($this->schema->getTables())))
        {
            $this->timeDependencyTable = $tdDefault;
        }
        if (!$this->timeDependencyTable) return;
        $t=$this->schema->getTables();
        if (!isset($t[$this->timeDependencyTable]) || !$t[$this->timeDependencyTable] instanceof Table)
        {
            throw new Exception\InvalidModel("Time dependency table {$this->timeDependencyTable} configured for table {$this->name} not found or not a table");
        }
        $t[$this->timeDependencyTable]->setIsTimeDependency(TRUE);
    }

    public function setIsTimeDependency($isDependency)
    {
        $this->isTimeDependency = $isDependency;
    }


    public function getWrapperClass()
    {
        $w = parent::getWrapperClass();
        if ($w !== NULL) return $w;
        if ($this->timeDependencyTable) return '\\WDB\\Wrapper\\TimeDependentTable';
        return NULL;
    }

    public function getTimeDependencyTable()
    {
        $t = $this->schema->getTables();
        return $t[$this->timeDependencyTable];
    }

    public function getForeignKeys()
    {
        return $this->tableColumns->foreign;
    }

    public function isWebUIAccessible()
    {
        return !$this->isTimeDependency && parent::isWebUIAccessible();
    }
}
